package utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysQuestion;
import com.ruoyi.common.core.domain.entity.SysQuestionDomain;
import com.ruoyi.common.core.domain.entity.SysQuestionRecord;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.domain.vo.DomainInfoItemVo;
import com.ruoyi.system.domain.vo.QuestionResultVo;
import com.ruoyi.system.dto.OptionConfig;
import com.ruoyi.system.dto.QuestionDomainScore;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * @author lwq
 * @ClassName ScoreUtils.java
 * @Description //TODO $
 * @createTime 2023-06-18 09:22
 */
public class ScoreUtils {

    public static String getScore(SysQuestion question) {
        if (question == null)
            return "0";
        String detail = question.getDetail();

        JSONObject jsonObject = JSONObject.parseObject(detail);
        String tag = jsonObject.getString("tagIcon");
        JSONArray options = jsonObject.getJSONArray("options");

        List<OptionConfig> optionConfigs= JSONArray.parseArray(question.getOptionConfig(),OptionConfig.class);


        List<SysQuestionRecord> records = question.getRecords();

        if (records == null || records.size() == 0)
            return "0";

        BigDecimal score=new BigDecimal("0.00");

        if ("radio".equals(tag)) {
            for (SysQuestionRecord record : records) {
                Integer index = Integer.parseInt(record.getAnswer());
                // 答案对于选项value,非下标
              //  JSONObject option = options.getJSONObject(index);
                JSONObject option=(JSONObject) options.stream().filter(
                        jsonobject->
                            index.equals(((JSONObject)jsonobject).getInteger("value"))

                ).findFirst().get();
                for (OptionConfig optionConfig : optionConfigs) {
                    if(option.get("value").equals(optionConfig.getValue())){
                        score=score.add(new BigDecimal(optionConfig.getScore()));
                        break;
                    }
                }

                // 只取第一个答题记录
                break;
            }

            return score.toString();
        }

        if ("checkbox".equals(tag)) {


            for (SysQuestionRecord record : records) {
                String anwser = record.getAnswer();
                if(anwser==null||anwser.length()<=2) {
                   // score += 0;
                    break;
                }

                anwser = anwser.substring(1, anwser.length()-1);

                String[] indexs = anwser.split(",");

                List<Integer> list = Stream.of(indexs).map(Integer::parseInt).collect(Collectors.toList());

              //  List<String> list = Arrays.asList(indexs);


                for (Integer index:list){
                   // JSONObject option = options.getJSONObject(index);

                    JSONObject option=(JSONObject) options.stream().filter(
                            jsonobject->
                                    index.equals(((JSONObject)jsonobject).getInteger("value"))

                    ).findFirst().get();

                    for (OptionConfig optionConfig : optionConfigs) {
                        if(option.get("value").equals(optionConfig.getValue())){
                            score=score.add(new BigDecimal(optionConfig.getScore()));
                            break;
                        }
                    }
                }

                // 只取第一个答题记录
                break;
            }
            return score.toString();
        }
        return "0";
    }


    public static QuestionDomainScore getFirstScore(SysQuestionDomain questionDomain, List<QuestionDomainScore> questionDomainScores){

        QuestionDomainScore questionDomainScore=new QuestionDomainScore();
        questionDomainScore.setDomainId(questionDomain.getDomainId());
        questionDomainScore.setDomainName(questionDomain.getDomainName());
        questionDomainScore.setTotalScore(questionDomain.getWeight());
        Integer weight=questionDomain.getWeight();

        BigDecimal score=new BigDecimal("0.00");

        for (QuestionDomainScore questionDomainScore1 : questionDomainScores) {
            score= score.add(new BigDecimal(questionDomainScore1.getScore()));

        }
        score=score.multiply(new BigDecimal(weight)).multiply(new BigDecimal("0.01"));
        questionDomainScore.setScore(score.toString());
        return questionDomainScore;
    }




    public static QuestionDomainScore getSecondScore(SysQuestionDomain sysQuestionDomain,List<SysQuestion> questions) {


        QuestionDomainScore questionDomainScore=new QuestionDomainScore();
        questionDomainScore.setDomainId(sysQuestionDomain.getDomainId());
        questionDomainScore.setDomainName(sysQuestionDomain.getDomainName());
        questionDomainScore.setParentId(sysQuestionDomain.getParentId());
        questionDomainScore.setTotalScore(sysQuestionDomain.getWeight());
        Integer weight=sysQuestionDomain.getWeight();

        BigDecimal score=new BigDecimal("0.00");

        for (SysQuestion sysQuestion : questions) {
            score=score.add(new BigDecimal(getScore(sysQuestion)));
        }

        score=score.multiply(new BigDecimal(weight)).multiply(new BigDecimal("0.01"));
        questionDomainScore.setScore(score.toString());
        return questionDomainScore;
    }

    public static QuestionDomainScore getDomainScore(SysQuestionDomain sysQuestionDomain,List<SysQuestion> questions) {


        QuestionDomainScore questionDomainScore=new QuestionDomainScore();
        questionDomainScore.setDomainId(sysQuestionDomain.getDomainId());
        questionDomainScore.setDomainName(sysQuestionDomain.getDomainName());
        questionDomainScore.setParentId(sysQuestionDomain.getParentId());
        questionDomainScore.setTotalScore(sysQuestionDomain.getWeight());
        System.out.println("====questions==="+questions.size());

        BigDecimal score=new BigDecimal("0.00");

        String content="";

        for (SysQuestion sysQuestion : questions) {
            QuestionResultVo questionResult=getWeightScore(sysQuestion);
            if(questionResult!=null){
                score=score.add(new BigDecimal(questionResult.getScore()));
                if(content.equals("")){
                    content=content+questionResult.getContent();
                }else{
                    content=content+","+questionResult.getContent();
                }

            }

        }

        System.out.println(score.toString());
        questionDomainScore.setScore(score.toString());
        questionDomainScore.setContent(content);

        System.out.println(questionDomainScore.toString());
        return questionDomainScore;
    }


    public static QuestionResultVo getWeightScore(SysQuestion question) {
        if (question == null){
            return null;
        }

        List<SysQuestionRecord> records = question.getRecords();

        if (records == null || records.size() == 0){
            return null;
        }

        // 优先取本人的，本人缺失取其他人任意一条
        SysQuestionRecord sysQuestionRecord=null;
        for (SysQuestionRecord record : records) {
            if(record.getUserId().equals(getLoginUser().getUserId())){
                sysQuestionRecord=record;
                break;
            }
        }
        if(sysQuestionRecord==null){
            sysQuestionRecord=records.get(0);
        }

        System.out.println("===records==="+records.size());

        QuestionResultVo questionResultVo=new QuestionResultVo();

        String detail = question.getDetail();

        JSONObject jsonObject = JSONObject.parseObject(detail);
        String tag = jsonObject.getString("tagIcon");
        JSONArray options = jsonObject.getJSONArray("options");
        System.out.println("====questionId==="+question.getQuestionId());
        if(question.getWeight()==null|| question.getOptionConfig()==null){
            return null;
        }
        String weight=question.getWeight();

        List<OptionConfig> optionConfigs= JSONArray.parseArray(question.getOptionConfig(),OptionConfig.class);

        BigDecimal score=new BigDecimal("0.00");

        String content="";
        if ("radio".equals(tag)) {
            Integer index = Integer.parseInt(sysQuestionRecord.getAnswer());
            // JSONObject option = options.getJSONObject(index);

            JSONObject option=(JSONObject) options.stream().filter(
                    jsonobject->
                            index.equals(((JSONObject)jsonobject).getInteger("value"))

            ).findFirst().get();

            for (OptionConfig optionConfig : optionConfigs) {
                if(option.get("value").equals(optionConfig.getValue())){
                    score=score.add(new BigDecimal(optionConfig.getScore()));
                    content=content+optionConfig.getDes();
                    break;
                }
            }

            questionResultVo.setScore(score.multiply(new BigDecimal(weight)).toString());
            questionResultVo.setContent(content);
            System.out.println("===questionResultVo==="+questionResultVo.toString());
            return questionResultVo;
        }
        return null;
    }


    /**
     * 对list数据进行分组
     * @param srcList
     * @param comparator
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> groupDataByCondition(List<T> srcList, Comparator<? super T> comparator) {

        List<List<T>> resultList = new ArrayList<>();

        for (int i = 0; i < srcList.size(); i++) {
            boolean isFindInCurrentGroups = false;
            //1.在现有组中查找
            for (int groupIndex = 0; groupIndex < resultList.size(); groupIndex++) {
                if (resultList.get(groupIndex).size() == 0 ||
                        comparator.compare(resultList.get(groupIndex).get(0), srcList.get(i)) == 0) {
                    //没有直接添加或者与第j组第一个匹配
                    resultList.get(groupIndex).add(srcList.get(i));
                    isFindInCurrentGroups = true;
                    break;
                }
            }
            //2.在现有组中没查找到
            if (!isFindInCurrentGroups) {
                List<T> newGroupList = new ArrayList<>();
                newGroupList.add(srcList.get(i));
                resultList.add(newGroupList);
            }
        }

        return resultList;
    }

    public static void main(String[] args) {
        BigDecimal score=new BigDecimal("750");
        BigDecimal bigDecimal=new BigDecimal("100000");
        BigDecimal procedureFee=score.divide(bigDecimal);

        System.out.println( score.multiply(new BigDecimal("0.00001")).toString());
        System.out.println(procedureFee.toString());
        System.out.println(String.valueOf(1*0.00001));

        SysQuestionRecord sysQuestionRecord=null;
        if (sysQuestionRecord == null) {
            System.out.println("对象为空，执行错误处理或返回默认值");
        } else {
            // 对象不为空，执行其他操作
            System.out.println("对象不为空");
        }
    }
}
